package com.example.demo.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * 重写 org.springframework.beans.BeanUtils 的 copyProperties(Object source, Object target) 方法
 * 从model复制属性到pojo中时,model中为null的属性不复制pojo中
 *
 * @author Liunh
 */
public class BeanUtil extends org.springframework.beans.BeanUtils {

    public static <T> Set<String> getEntityFields(Class<T> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        Set<String> fieldsSet = new HashSet<>();
        Arrays.stream(fields).filter(field -> !"serialVersionUID".equals(field.getName()) && !field.getName().startsWith("this$")).forEach(field -> {
            fieldsSet.add(field.getName());
        });
        return fieldsSet;
    }

    /**
     * 转化为List<T>
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> parseArray(Object data, Class<T> clazz) {
        String jsonString = JacksonUtil.beanToJson(data);
        return JacksonUtil.jsonToList(jsonString, clazz);
    }

    /**
     * 转化为T
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T parseObject(Object data, Class<T> clazz) {
        String jsonString = JacksonUtil.beanToJson(data);
        return JacksonUtil.jsonToBean(jsonString, clazz);
    }

    /**
     * 转化为T
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T parseObject(Object data, Class<T> clazz, String pattern) {
        String jsonString = JacksonUtil.beanToJson(data, pattern);
        return JacksonUtil.jsonToBean(jsonString, clazz);
    }

    /**
     * 从org.springframework.beans.BeanUtils类中直接复制过来
     * 不复制null，但复制空白字符窜""
     *
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyProperties(Object source, Object target) throws BeansException {
        copyProperties(source, target, null, false, (String[]) null);
    }

    /**
     * 不复制null和空白字符窜""
     *
     * @param source
     * @param target
     * @throws BeansException
     */
    public static void copyPropertiesExcludeNullAndEmpty(Object source, Object target) throws BeansException {
        copyProperties(source, target, null, true, (String[]) null);
    }

    /**
     * 从org.springframework.beans.BeanUtils类中直接复制过来,修改部分代码
     *
     * @param source
     * @param target
     * @param editable
     * @param emptyExclude     排除空白字符窜
     * @param ignoreProperties
     * @throws BeansException
     */
    private static void copyProperties(Object source, Object target, Class<?> editable, boolean emptyExclude, String... ignoreProperties) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        if (editable != null) {
            if (!editable.isInstance(target)) {
                throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
            }
            actualEditable = editable;
        }

        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
        for (PropertyDescriptor targetPd : targetPds) {
            Method writeMethod = targetPd.getWriteMethod();
            if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
                    Method readMethod = sourcePd.getReadMethod();
                    //if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                    if (readMethod != null) {
                        try {
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }
                            Object value = readMethod.invoke(source);
                            // 判断被复制的属性是否为null, 如果不为null才复制
                            if (value != null) {
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                } else if (value instanceof List && emptyExclude && ((List<?>) value).size() == 0) {
                                    continue;
                                } else if (value instanceof Set && emptyExclude && ((Set<?>) value).size() == 0) {
                                    continue;
                                } else if (value instanceof Map && emptyExclude && ((Map<?, ?>) value).size() == 0) {
                                    continue;
                                } else if (value instanceof String && emptyExclude && StringUtils.isBlank(String.valueOf(value))) {
                                    continue;
                                } else {
                                    Class<?>[] writeParameterTypes = writeMethod.getParameterTypes();
                                    Class<?> returnType = readMethod.getReturnType();
                                    if (!returnType.getName().equals(writeParameterTypes[0].getName()) && writeParameterTypes.length == 1) {
                                        if ((value instanceof Date || returnType.getName().contains("Date")) && writeParameterTypes[0].getName().contains("String")) {
                                            value = DateUtil.date2Str((Date) value, DateUtil.DATE_FORMAT_DEFAULT);
                                        }
                                        if ((value instanceof String || returnType.getName().contains("String")) && writeParameterTypes[0].getName().contains("Date")) {
                                            value = DateUtil.str2Date(String.valueOf(value), DateUtil.DATE_FORMAT_DEFAULT);
                                        }
                                    }
                                }
                                writeMethod.invoke(target, value);
                            }
                        } catch (Throwable ex) {
                            throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                        }
                    }
                }
            }
        }
    }

}
